package com.ktjy.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


import java.io.IOException;
import java.io.InputStream;
public class MybatisUtil {
    static SqlSessionFactory factory=null;
    static {
        try {
            //1.创建一个工厂构建对象
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
            //2.加载mybatis的核心配置文件
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            //2.创建工厂对象
            factory=sqlSessionFactoryBuilder.build(is);
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }
    public static SqlSession getSession(){
        SqlSession session=factory.openSession();
        return session;
    }
    public static void closeSession(SqlSession session) {
        if(session!=null){
            session.close();
        }
    }
}
